﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using Northwind.NET.Model;
using Northwind.NET.Settings;
using System.Windows.Forms;
using System.IO;
using System.Data.Common;
using System.Data;

namespace Northwind.NET.EDM.FE.WinForms.Controls
{
    public partial class EmployeesUserControl : BaseUserControl
    {
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            LoadEmployees();
        }

        private void LoadEmployees()
        {
            using (DbConnection connection = Factory.CreateConnection())
            {
                connection.ConnectionString = ConnectionString;
                DbDataAdapter adapter = Factory.CreateDataAdapter();
                DbCommand command = Factory.CreateCommand();
                command.Connection = connection;
                command.CommandText = "SELECT ID, LastName, FirstName, Title, TitleOfCourtesy, BirthDate, " +
                                        "HireDate, Address, City, Region, PostalCode, Country, HomePhone, Extension, " +
                                        "Photo, Notes, ReportsTo FROM Employees";

                adapter.SelectCommand = command;

                DataSet dataset = new DataSet();
                dataset.Tables.Add("Employees");
                adapter.Fill(dataset.Tables["Employees"]);

                this.employeeBindingSource.DataSource = dataset.Tables["Employees"];
            }
        }
        public EmployeesUserControl()
        {
            InitializeComponent();
        }

        public override string FormCaption { get { return Settings.Resources.EmployeesFormCaption; } }
        public override dynamic GetEntitySet(ObjectContext context)
        {
            return new Model.Employee();
        }

        public override BindingSource UserControlBindingSource { get { return employeeBindingSource; }}


        private string _imagePath = String.Empty;


        private void EmployeesUserControl_Load(object sender, EventArgs e)
        {
            if (this.DesignMode) return;
 
            LoadReportsToFullList();
        }

        internal override void SetBindingSource()
        {
            _imagePath = Northwind.NET.Utilities.Context.ExecutingAssemblyFolderName + @"Pictures";
            this.firstNameTextBox.TextChanged += new EventHandler(FillFullNameTitleBar);
            this.lastNameTextBox.TextChanged += new EventHandler(FillFullNameTitleBar);

            var dataSet = new Model.Employee();
            var firstRecord = dataSet;//.FirstOrDefault();
            UserControlBindingSource.DataSource = dataSet;
            if (firstRecord != null)
            {
                //setPictureFile(firstRecord.PhotoPath);  
            }
        }

        private void LoadReportsToFullList()
        {
           //this.re  reportsToComboBox.
            //_employeeDataTable = employeeTableAdapter.GetData();

            FillReportsToComboBox(this, new EventArgs());
        }

        //private void employeeBindingNavigatorSaveItem_Click(object sender, EventArgs e)
        //{
        //    this.Validate();
        //    this.employeeBindingSource.EndEdit();
        //    this.tableAdapterManager.UpdateAll(this.dataModelDataSet);
        //    // Requery list of possible employees to report to.
        //    LoadReportsToFullList();
        //    FillReportsToComboBox(null, null);
        //}

        private void setPictureFile(string fileName)
        {
            bool hasPicture = Convert.ToBoolean(fileName.Length);
            if (hasPicture == false)
            {
                // No picture.
                this.imagePictureBox.Image = null;
            }
            else
            {
                // Retrieve picture.
                string fullPath = Path.Combine(_imagePath, fileName);
                this.imagePictureBox.Load(fullPath);
            }
            // not used => this.removePictureButton.Enabled = hasPicture;
        }

        private void pictureTextBox_TextChanged(object sender, EventArgs e)
        {
            TextBox textBox = (TextBox)sender;
            string fileName = textBox.Text;

            setPictureFile(fileName);             
        }

        private void FillFullNameTitleBar(object sender, EventArgs e)
        {
            // Set full name in title bar.
            this.fullNameTextBox.Text = this.firstNameTextBox.Text + " " + this.lastNameTextBox.Text;
        }

        private void FillReportsToComboBox(Object sender, EventArgs e)
        {
        }

        private void employeeBindingSource_PositionChanged(object sender, EventArgs e)
        {
            FillReportsToComboBox(null, null);
        }

        private bool SelectPictureFile()
        {
            string path = _imagePath;
            string file = this.pictureTextBox.Text;
            // Reset file dialogue to always open at InitialDirectory.
            this.openFileDialog1.Reset();
            this.openFileDialog1.InitialDirectory = path;
            this.openFileDialog1.FileName = file;
            this.openFileDialog1.Title = "Select picture";
            //this.openFileDialog1.AutoUpgradeEnabled = true;
            this.openFileDialog1.Filter = @"All files (*.*)|*.*";
            this.openFileDialog1.Multiselect = false;
            //this.openFileDialog1.ValidateNames = true;
            this.openFileDialog1.RestoreDirectory = true;
            DialogResult result = this.openFileDialog1.ShowDialog(this);

            if (result == DialogResult.OK)
            {
                try
                {
                    file = this.openFileDialog1.SafeFileName;
                    if (this.openFileDialog1.FileName.Equals(Path.Combine(path, file)))
                    {
                        this.pictureTextBox.Text = file;
                        return true;
                    }
                    else
                    {
                        MessageBox.Show("Pictures can only be selected from the folder " + path + ".", "Wrong folder", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                catch
                {
                    MessageBox.Show("The file " + file + " can not be read.", "Error when retrieving file", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    this.pictureTextBox.Text = null;
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        private void openPictureButton_Click(object sender, EventArgs e)
        {
            // not used

            SelectPictureFile();
        }

        private void removePictureButton_Click(object sender, EventArgs e)
        {
            // not used

            DialogResult result;
            // Confirm removal of the picture.
            result = MessageBox.Show(
                (string)"Remove picture of this employee?",
                (string)"Removal of picture",
                MessageBoxButtons.OKCancel,
                MessageBoxIcon.Question,
                MessageBoxDefaultButton.Button2);
            if (result.Equals(DialogResult.OK))
            {
                this.pictureTextBox.Text = null;
            }
        }


    }
}
